<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Goods;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;
use DB;

class CategoryController extends Controller
{

    use ApiResponse;

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $list = Category::query()->paginate();
        return view('admin.category.index', [
            'lists' => $list
        ]);
    }

    public function getList()
    {
        $list = Category::query()->paginate();
        return $this->success($list);
    }

    public function create(Request $request)
    {

        return view('admin.category.create', []);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string|max:255',
        ], [

        ]);
        try {
            $category = Category::query()->updateOrCreate([
                'name' => $request['name'],
            ]);
        } catch (\Throwable $throwable) {
            \Log::error($throwable);
            return $this->error($throwable->getMessage());

        }
        return $this->success();
    }

    public function update(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string|max:255',
            'id' => 'required',
        ], [
        ]);
        $category = Category::query()->where('id', $request['id'])->first();
        if (!$category) {
            return $this->error('记录不存在');
        }

        $category->update(['name' => $request['name']]);

        return $this->success();
    }

    public function destroy(Request $request)
    {
        $categoryId = $request['category_id'] ?? 0;
        Category::query()->where('id', $categoryId)->delete();
        Goods::query()->where('type_id', $categoryId)->update(['type_id' => 0]);
        return $this->success([], '删除成功');
    }
}

